#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 1005
#define ERROR -1
#define INFINITY 65535  //双字节无符号整数的最大值
typedef int Vertex;//顶点下标表示顶点
typedef int WeightType;//边的权值
typedef char DataType;//顶点储存的数据类型
int N, M, A[MaxVertexNum][MaxVertexNum], dist[MaxVertexNum];
int FindMinDist() {
	int MinDist = INFINITY, MinV;
	for(int V = 0; V < N; V++) {
		//如果V未被收录且dist[V]更小
		if( dist[V] != 0 && dist[V] < MinDist ) {
			MinDist = dist[V];
			MinV = V;
		}
	}
	if( MinDist < INFINITY )
		return MinV;
	else return ERROR;
}
int Prim() {
	WeightType TotalWeight, V, W, VCount;
	//初始化，默认初始点下标为0
	for( V = 0; V < N; V++ ) {
		dist[V] = A[0][V];
		//Parent[V] = 0;	//暂定所有顶点的父结点都是0
	}
	TotalWeight = 0;	//初始化权重和
	VCount = 0;			//初始化收录的顶点数
	dist[0] = 0;		//将初始点0收录
	VCount++;
	//Parent[0] = -1;
	while(1) {
		//V = 未被收录顶点中dist最小者
		V = FindMinDist();
		//若V不存在，则结束
		if( V == ERROR )
			break;
		//收录V
		TotalWeight += dist[V];
		dist[V] = 0;
		VCount++;
		for( W = 0; W < N; W++)
			//若W未被收录且是V的邻接点
			if( dist[W] != 0 && A[V][W] < INFINITY )
				//如果收录V使得dist[W]变小
				if( A[V][W] < dist[W] ) {
					dist[W] = A[V][W];
					//Parent[W] = V;
				}
	}
	if( VCount < N )
		TotalWeight = ERROR;
	return TotalWeight;
}
int main(){
	int a, b, k;
	scanf("%d %d", &N, &M);
	//初始化
	for(int i = 0; i < N; i++){
		dist[i] = INFINITY;
		//Parent[i] = -1;
		for(int j = 0; j < N; j++)
			A[i][j] = INFINITY;
	}
	//read
	for(int i = 0; i < M; i++) {
		scanf("%d %d", &a, &b);
		scanf("%d", &A[--a][--b]);		//题中编号从1开始
		A[b][a] = A[a][b];
	}
	k = Prim();
	if( k == ERROR )
		printf("-1\n");
	else
		printf("%d\n", k);
	return 0;
}
//公路村村通